import numpy as np
import cv2 as cv

# 读取视频文件
cap = cv.VideoCapture('bike.mp4')

# 循环播放视频文件，同时显示原视频及其对应的灰度图
while cap.isOpened():
    # 逐帧读取视频，ret 为布尔值，表示是否成功读取帧，frame 为当前帧的图像数据
    ret, frame = cap.read()
    if not ret:
        print("没有内容，退出啦 :) ")
        break

    # 使用 cv2.cvtColor() 将当前帧的彩色图像转换为灰度图
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

    # 获取每一帧图像的傅里叶系数以及振幅谱
    fCoefs = np.fft.fft2(gray)
    mag_spec = np.abs(fCoefs)
    mag_spec_sorted = np.sort(mag_spec.ravel())
    cv.imshow('origin', gray)
    # 定义压缩列表
    keep_list = [0.5,0.05]
    for keep in keep_list:
        thresh = mag_spec_sorted[int((1 - keep) * gray.size)]
        mask = mag_spec > thresh
        fCoefs_compressed = fCoefs * mask
        img_cp = np.fft.ifft2(fCoefs_compressed).real
        # 使用极大极小值归一的操作使得图像的像素回归到正常值的范围内
        img_max = img_cp.max()
        img_min = img_cp.min()
        img = (img_cp - img_min) / (img_max - img_min)
        cv.imshow(f"compressed_rate：{keep}", img)

    if cv.waitKey(1) == ord('q'):
        break

cap.release()
cv.destroyAllWindows()


